// pages/xiangqing/musice/miuses.ts
import geci from"../../../utils/geci"
Page({

  /**
   * 页面的初始数据
   */
  data: {
id:0 as any,  //获取跳转过来的id
shuju:null  as any,
show:true, //判断是否播放
text:null as any,  //全部歌词
gequci:[] as unknown, //时实歌词
isshow:false, //判断是否显示面板
//歌曲详情
  poster:'', //壁纸
  name:'', //歌曲名字
  author:'', //作者
  src:'', //地址
currentTime: "00:00",
  totalTime: "00:00",
  setp:0, //进度条的速度
  navState:0,//判断选中内容
  xggq:null as any , //相关歌曲
  xsgq:null as any , //相似歌曲
  jcpl:null as any , //精彩评论
  liang:0,//判断高亮
  gaodu:0//判断滚动高度
  },
  totalSeconds:0,//进度条长度
  bgManager: {} as WechatMiniprogram.BackgroundAudioManager,
  
  //音乐播放
  musice(){
    const a=this.data
    
    this.bgManager = wx.getBackgroundAudioManager();
    //监听歌曲
    this.bgManager.onTimeUpdate(() => {
      const curTime = this.bgManager.currentTime;
      const duration = this.bgManager.duration;  
      let val=this.formatTime(curTime)
      this.setData({
        setp:parseInt(`${(curTime/duration)*100}`),
        currentTime: this.formatTime(curTime),
      })
      this.geci(val)
    })
    //播放结束
    this.bgManager.onEnded(() => {
      this.setData({
        currentTime:"00:00",
        show:true
      })
   
    });
       // 监听音频缓冲事件
       this.bgManager.onWaiting(() => {
        wx.showToast({
          title: "网络较慢...",
          icon: "none",
        });
      });
       // 监听音频资源可以播放了，缓冲了一定的数据时，可以播放了，不保证后面流畅播放
    this.bgManager.onCanplay(() => {
      const curTime = this.bgManager.currentTime;
      const duration = this.bgManager.duration;
      this.totalSeconds = duration;  
      let val=this.formatTime(curTime)
      this.setData({
        currentTime: this.formatTime(curTime),
        totalTime: this.formatTime(duration),
      });
      wx.hideToast();
      this.geci(val)
    });
    this.bgManager.src = this.data.src;
    this.bgManager.title = a.name;
    this.bgManager.coverImgUrl = a.poster;
this.data.show==true? this.bgManager.pause():this.bgManager.play()
   },
   //时间转换
   formatTime(seconds: number): string {
    // 将总秒数，转化为 分:秒 的形式
    let sec: number | string = parseInt(`${seconds % 60}`);
    sec = sec < 10 ? "0" + sec : sec + "";
    let min: number | string = parseInt(`${seconds / 60}`);
    min = min < 10 ? "0" + min : min + "";
    return `${min}:${sec}`;
  },
  //拖动播放
  tuodong(e:any){
    const curStep = e.detail.value;
    console.log(curStep);
    this.setData({ 
      step: curStep,
    });
    this.bgManager.seek((curStep / 100) * this.totalSeconds);  
 
  },
  //歌词同步
  geci(val:any){
    let a=this.data.text
    let d=val
    // console.log(val);
    
    a.forEach((item:any,i:number )=> {
      let b=item.time
      // let e=item.text
      let c=this.formatTime(b/1000)
     if (c==d) { 
       console.log(c);
       
    this.setData({
      liang:i,
      gaodu:i>1?((i-1)*33):i
    })
     }
    });  
     
  },
  xianshi(e:any){
    console.log(e);
    
   
  },

  onClose() {
    this.setData({ isshow: false });
  },
  //
  zuo(e:any){
    const id =e.currentTarget.dataset.id
console.log(id);
this.setData({
  isshow:true,
  navState:id
})
this.shuju()
  },
  //获取数据
  shuju() {
    let id =this.data.id.replace(/\s+/g,'')
    wx.request({
      url: `http://localhost:3000/simi/song?id=${this.data.id}`,
      method: "GET",
      success: (res: any) => {
        // console.log(res.data.songs);
        this.setData({
          xsgq:res.data.songs
        })
      },
    });
    wx.request({
      url:`http://localhost:3000/comment/new?`,
      method: "GET",
      data:{
        type:0,
        id:id,
  pageNo:1,
  pageSize:9,
      },
      success: (res: any) => {
        // console.log(res); 
        this.setData({
          jcpl:res.data.data.comments
        })
      },
    });

    //评论
        // //评论数据
        // wx.request({
        //   url:`http://localhost:3000/comment/playlist?id=${this.data.id}&offset=1&limit=10`,
        //   method:"GET",
        //   success:(res:any)=>{
        //     console.log(res);
            
        //   }
        // })

    wx.request({
      url: `http://localhost:3000/simi/playlist?id=${this.data.id}`,
      method: "GET",
      success: (res: any) => {
        // console.log(res.data.playlists);
        if (res.data.playlists.length!==0) {
          this.setData({
          xggq:res.data.playlists
        })
        }else{
          this.setData({
            xggq:[
              {
                coverImgUrl:"https://i0.hdslb.com/bfs/article/cb7b988d82bf6ed7d88ea49ced605ebad113f6f4.jpg@942w_531h_progressive.webp",
                playCount:990912,
                description:"宝贝别看了~",
                name:"未获取数据",
              }
            ]
          })
        }

        
      },
    });
  },

      navSwitch: function (e: any) {
    //  console.log(e);
        let index = e.currentTarget.dataset.index;
        this.setData({
          navState: index,
        });
     
      },
//滚动事件
scroll(e:any){
  console.log(e.detail.scrollTop);
  let gun=e.detail.scrollTop
  if (gun<=182) {
    this.setData({
      navState:0
    })
  }else if(gun<413&&gun>182){
    this.setData({
      navState:1
    })
  }else{
    this.setData({
      navState:2
    })
  }

  // .....
  let scrollTop = 0;
  const query = wx.createSelectorQuery();
  query.selectViewport().scrollOffset();
  query.exec(function (res) {
     scrollTop = res[0].scrollTop;
   });
 query.select('#cao').boundingClientRect(res => {
  scrollTop=res.top
       wx.pageScrollTo({
         scrollTop: res.top, 
         duration: 0,
       })
       console.log(res);
       
      //  console.log('当前距离',scrollTop,"实际高度",res.top-169.324996);
       
 }).exec();

},
  

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options:any) {
 
    this.setData({
      id:options.id,
  
    })
this.huoqu()

      },
      //换曲
      guanqu:function(e:any){
        let abc=e.detail
        console.log(abc);
        this.setData({
          id:abc,
          isshow:false
        })
        this.huoqu()
        setTimeout(() => {
          this.bofang()
        }, 1000);
      },
 

//获取数据
      huoqu(){
        wx.request({
          url:`http://localhost:3000/song/detail?ids=${this.data.id}`,
          method:'GET',
          success:(res:any)=>{
            // console.log(res.data.songs);
           this.setData({
             shuju:res.data.songs,
             poster:res.data.songs[0].al.picUrl,
             name:res.data.songs[0].name

           })
          } })
          wx.request({
            url:`http://localhost:3000/lyric?id=${this.data.id}`,
            method:'GET',
            success:(res:any)=>{
              let a=res.data.lrc.lyric           
             this.setData({
               text:geci.geci(a)
             })
            } })
            wx.request({
              url:`http://localhost:3000/song/url?id=${this.data.id}`,
              method:'GET',
              success:(res:any)=>{
               this.setData({
                src:res.data.data[0].url
               })
              } })
          
      },
      //按钮播放

      bofang(){
        this.setData({
          show:false
        })
        this.musice()
      },
      kaishi(){
        this.setData({
          show:true
        })
        this.musice()
      
      },

      tiao(){
        wx.redirectTo({
          url:"../../tiaozhuan/tianone/tiaozhuanone"
        })
      }

     
     

  
})